package common.test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GroupAnagram {

    public List<List<String>> groupAnagrams(String[] strs) {
        if (strs == null || strs.length == 0) {
            return new ArrayList<>();
        }
        Map<String, List<String>> map = new HashMap<>();
        for (String str : strs) {
            int[] counts = new int[26];
            char[] ch = str.toCharArray();
            for (char c : ch) {
                counts[c - 'a']++;
            }
            StringBuilder keyBuilder = new StringBuilder();
            for (int i = 0; i < 26; i++) {
                if (counts[i] != 0) {
                    keyBuilder.append(counts[i]).append(i + 'a');
                }
            }

            List<String> list = map.getOrDefault(keyBuilder.toString(), new ArrayList<>());
            list.add(str);
            map.put(keyBuilder.toString(), list);
        }
        return new ArrayList<>(map.values());
    }
}
